<script setup lang="ts">
import { reactive, ref, h } from 'vue';
import { NButton, NPopconfirm, NSpace, NTag } from 'naive-ui';
import { deleteJob, fetchJobList, startJob } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import JobOperateDrawer from './modules/job-operate-drawer.vue';
import JobInstanceDrawer from './modules/job-instance-drawer.vue';
import DagDesignerModal from './modules/dag-designer-modal.vue';

const appStore = useAppStore();

const { columns, columnChecks, data, loading, pagination, getData, getDataByPage, mobilePagination } = useTable({
  apiFn: fetchJobList,
  apiParams: {
    pageNum: 1,
    pageSize: 10
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'id',
      title: 'ID',
      align: 'center',
      width: 80
    },
    {
      key: 'name',
      title: '作业名称',
      align: 'center',
      minWidth: 150
    },
    {
      key: 'jobType',
      title: '作业类型',
      align: 'center',
      width: 100,
      render: row => {
        const typeMap: Record<string, { label: string; type: NaiveUI.ThemeColor }> = {
          ETL: { label: 'ETL', type: 'primary' },
          SQL: { label: 'SQL', type: 'info' },
          SCRIPT: { label: '脚本', type: 'warning' }
        };
        const config = typeMap[row.jobType] || { label: row.jobType, type: 'default' };
        return h(NTag, { type: config.type }, () => config.label);
      }
    },
    {
      key: 'scheduleType',
      title: '调度类型',
      align: 'center',
      width: 120,
      render: row => {
        if (!row.scheduleType) return '-';
        const typeMap: Record<string, string> = {
          CRON: '定时调度',
          DEPENDENCY: '依赖调度',
          MANUAL: '手动触发'
        };
        return typeMap[row.scheduleType] || row.scheduleType;
      }
    },
    {
      key: 'status',
      title: '状态',
      align: 'center',
      width: 100,
      render: row => {
        return row.status === 1 ? h(NTag, { type: 'success' }, () => '启用') : h(NTag, { type: 'error' }, () => '禁用');
      }
    },
    {
      key: 'description',
      title: '描述',
      align: 'center',
      minWidth: 200,
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'createTime',
      title: '创建时间',
      align: 'center',
      width: 180
    },
    {
      key: 'operate',
      title: '操作',
      align: 'center',
      width: 300,
      render: row => {
        return h(NSpace, { justify: 'center' }, () => [
          h(NButton, { size: 'small', type: 'primary', onClick: () => handleStart(row.id) }, () => '启动'),
          h(NButton, { size: 'small', onClick: () => handleViewInstances(row.id) }, () => '实例'),
          h(NButton, { size: 'small', onClick: () => handleEdit(row.id) }, () => '编辑'),
          h(NPopconfirm, { onPositiveClick: () => handleDelete(row.id) }, {
            default: () => '确认删除',
            trigger: () => h(NButton, { size: 'small', type: 'error' }, () => '删除')
          })
        ]);
      }
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // @ts-ignore
} = useTableOperate(data, getData);

const instanceDrawerVisible = ref(false);
const selectedJobId = ref<number>();
const dagDesignerVisible = ref(false);

async function handleDelete(id: number) {
  await deleteJob(id);
  onDeleted();
}

async function handleStart(id: number) {
  await startJob(id, 'MANUAL');
  window.$message?.success('作业已启动');
  getData();
}

function handleViewInstances(jobId: number) {
  selectedJobId.value = jobId;
  instanceDrawerVisible.value = true;
}

function handleDesignDag(jobId?: number) {
  if (jobId) {
    selectedJobId.value = jobId;
  }
  dagDesignerVisible.value = true;
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard :title="$t('route.dataplatform_job')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @delete="onBatchDeleted"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="962"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <template #footer>
        <TableFooterPagination v-model:pagination="pagination" :loading="loading" @change="getDataByPage" />
      </template>
    </NCard>
    <JobOperateDrawer
      v-model:visible="drawerVisible"
      :operate-type="operateType"
      :row-data="editingData"
      @submitted="getData"
    />
    <JobInstanceDrawer v-model:visible="instanceDrawerVisible" :job-id="selectedJobId" />
    <DagDesignerModal v-model:visible="dagDesignerVisible" :job-id="selectedJobId" @submitted="getData" />
  </div>
</template>

<style scoped></style>
